<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\TenantProduct\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Tenant\Contract\TenantMenuPackageContract;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;

/**
 * 套餐管理- 创建提交.
 *
 * Class StoreLogic
 */
class StoreLogic
{
    /**
     * @Inject
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @Inject
     * @var TenantMenuPackageContract
     */
    protected $tenantMenuPackageService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @param array $params 请求参数
     * @return array 响应数组
     */
    public function handle(array $params): array
    {
        if ($params['marketPrice'] < $params['price']) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '套餐原价不能小于套餐现价');
        }
        // 数据操作
        Db::beginTransaction();
        try {
            // sku
            $skuId = $this->insertSkuData($params);
            // attribute&value
            $attributeIds = $this->insertAttributeData($params['attributes'], $skuId);
            // sku->attributes
            $this->tenantProductSkuService->updateTenantProductSkuById($skuId, ['attributes' => implode(',', $attributeIds)]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '账户创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '账户创建失败');
        }
        return [];
    }

    /**
     * 创建商品sku.
     * @param array $params 请求参数
     */
    private function insertSkuData(array $params): int
    {
        $data = [
            'spu_id' => $params['spuId'],
            'price' => $params['price'],
            'market_price' => $params['marketPrice'],
            'stock' => $params['stock'],
            'status' => 1,
            'audit_status' => $params['auditStatus'],
            'created_at' => date('Y-m-d H:i:s'),
        ];
        return $this->tenantProductSkuService->createTenantProductSku($data);
    }

    /**
     * 创建商品属性.
     */
    private function insertAttributeData(array $attributes, int $skuId): array
    {
        // 处理商品属性
        $arrValueIds = [];
        foreach ($attributes as $item) {
            $attributeData = [
                'name' => $item['attributeName'],
                'type' => 2,
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $arrId = $this->tenantProductSkuService->createTenantProductSkuAttribute($attributeData);
            $valueData = [
                'attribute_id' => $arrId,
                'value' => $item['attributeValue'],
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $arrValueIds[] = $this->tenantProductSkuService->createTenantProductSkuValue($valueData);
            // 租户菜单处理
            if ($item['attributeName'] === '套餐功能') {
                $data = [
                    'sku_id' => $skuId,
                    'menu_id' => $item['attributeValue'],
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $this->tenantMenuPackageService->createTenantMenuPackage($data);
            }
        }
        return $arrValueIds;
    }
}
